let { getPreviousNode, handleOutFormat } = require("./index.js");
const TYPECONDITION = "condition";
const handleGetItemPrev = (arrs, originData) => {
  let getPreArrs = (dataArrs) => {
    let tempArr = [];
    if (!dataArrs || !dataArrs.length) return;
    dataArrs.forEach((element) => {
      let pre = getPreviousNode(element.prevId, originData);
      let { content, nodeId, type, outgoing } = pre || {};
      let { content: cct, nodeId: cnd, type: cte } = element || {};
      if (!outgoing || !outgoing.length) outgoing = [];
      outgoing = outgoing.concat(handleOutFormat(element));
      if (pre)
        tempArr.push({
          content,
          nodeId,
          type,
          outgoing,
        });
    });
    return tempArr;
  };
  // 合并下item的outgoing
  const MergeGo = (arr) => {
    let tempObj = {};
    arr.forEach((k) => {
      let { nodeId, outgoing } = k;
      if (!tempObj[nodeId]) tempObj[nodeId] = {};
      let { outgoing: ogSecond } = tempObj[nodeId] || {};
      if (!ogSecond) {
        tempObj[nodeId].outgoing = outgoing;
      } else {
        tempObj[nodeId].outgoing = tempObj[nodeId].outgoing.concat(outgoing);
      }
    });
    return tempObj;
  };
  // 处理节点下存在条件、其他节点并存的情况
  var delRepeatNode = (obj) => {
    for (k in obj) {
      let { outgoing: gArr } = obj[k] || {};
      let typeObj = {};
      gArr.forEach((i, index) => {
        typeObj[i.type] = index + 1;
      });
      if (typeObj[TYPECONDITION] && Object.keys(typeObj).length > 1) {
        let outingDeep = gArr.filter((k) => k.type !== TYPECONDITION);
        let goingRight = gArr.filter((k) => k.type === TYPECONDITION);
        obj[k].outgoing = goingRight;
        obj[k].outingDeep = outingDeep;
      }
    }
  };
  let resultArr = getPreArrs(arrs);
  // console.log(resultArr);
  let nodeIdArrWithGo = MergeGo(resultArr);
  console.log(nodeIdArrWithGo);

  delRepeatNode(nodeIdArrWithGo);
  return nodeIdArrWithGo;
};
module.exports = {
  handleGetItemPrev,
};
